# _*_ coding:utf-8 _*_
# @File  : variety.py
# @Time  : 2021-10-29  10:18
# @Author: zizle

from fastapi import APIRouter, Path, Body

from db import utils as dbutils
from db import FAConnection
from status import r_status

admin_variety_api = APIRouter()


@admin_variety_api.get('/{variety_id}/', summary='请求单个品种信息')
async def get_variety_information(variety_id: int = Path(..., ge=1)):
    db = FAConnection(conn_name='admin查询单个品种信息')
    sql = 'SELECT * FROM sys_variety WHERE id=%s;'
    v_data = db.query(sql, param=[variety_id], fetchone=True)[0]
    return {'code': r_status.SUCCESS, 'message': '获取品种的基本信息成功!', 'data': v_data}


@admin_variety_api.put('/{variety_id}/', summary='修改一个品种的信息')
async def modify_variety_information(variety_id: int = Path(..., ge=1), body_data: dict = Body(...)):
    accept_columns = ['category', 'exchange', 'variety_en', 'variety_name', 'price_unit', 'hand_amount', 'hand_unit',
                      'bail_rate', 'strategy_fund', 'is_active']
    update_data = dbutils.exclude_columns(body_data, accept_columns)
    # 若严谨:次数需验证body数据的合法性
    kv_sql = dbutils.create_sql(update_data)
    db = FAConnection(conn_name='admin更新品种信息')
    sql = 'UPDATE sys_variety SET ' + kv_sql + 'WHERE id=%(id)s LIMIT 1;'
    update_data['id'] = variety_id
    _, s = db.execute(sql, param=update_data)
    if s:
        return {'code': r_status.SUCCESS, 'message': '更新品种信息成功!'}
    return {'code': r_status.VALIDATE_ERROR, 'message': '更新品种信息失败!'}
